package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 添加好友
     * <p>
     * 1、保存数据到mongodb
     * 2、好友关系注册到环信
     *
     * @param friendId 需要添加的id
     * @return
     */

    public Boolean contactUser(Long friendId) {
        //获取用户对象
        User user = UserThreadLocal.get();
        //创建users对象
        Users users = new Users();
        users.setUserId(user.getId());  //用户id
        users.setFriendId(friendId);  //好友的id

        //保存数据到mongodb
        String id = usersApi.saveUsers(users);
        if (StringUtils.isNotEmpty(id)) {
            //注册好友关系到环信  请求注册好友关系的路径
            String targetUrl = url + "/user/huanxin/contacts/" + users.getUserId() + "/" + users.getFriendId();
            ResponseEntity<Void> responseEntity = restTemplate.postForEntity(targetUrl, null, Void.class);

            //响应成功，返回true
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                return true;
            }

            return false;

        }
        return false;
    }

    /**
     * 查询联系人列表
     *
     * @param page
     * @param pageSize
     * @param keyword  查询关键字
     * @return 分两种情况. 一是带关键字查询   二是不带关键字查询
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {

        //获取当前用户
        User user = UserThreadLocal.get();

        //创建集合封装好友关系表数据
        List<Users> usersList = null;
        //如果查询条件不为空
        if (StringUtils.isNotEmpty(keyword)) {
            //不为空
            //根据用户id查询所有的用户
            usersList = usersApi.queryAllUsersList(user.getId());
        } else {
            //为空
            PageInfo<Users> pageInfo = usersApi.queryUsersList(user.getId(), page, pageSize);
            usersList = pageInfo.getRecords();
        }

        //创建集合封装好友id
        List<Long> fUserIds = new ArrayList<>();
        for (Users users : usersList) {
            fUserIds.add(users.getFriendId());
        }

        //数据库查询好友信息

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.in("user_id", fUserIds);
        //再判断keyword是否为空
        if (StringUtils.isNotEmpty(keyword)) {
            //查询nickname字段
            wrapper.like("nick_name", keyword);
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);

        //创建Contacts集合
        List<Contacts> contactsList = new ArrayList<>();
        //如果keyword为空
        if (StringUtils.isEmpty(keyword)) {
            for (Users users : usersList) {
                for (UserInfo userInfo : userInfoList) {
                    if (users.getFriendId().longValue() == userInfo.getUserId().longValue()) {   //一一对一
                        Contacts contacts = new Contacts();
                        contacts.setAge(userInfo.getAge());  //年龄
                        contacts.setAvatar(userInfo.getLogo());  //头像
                        contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));  //城市
                        contacts.setGender(userInfo.getSex().toString()); //性别
                        contacts.setNickname(userInfo.getNickName()); //名称
                        contacts.setUserId(userInfo.getUserId().toString());

                        contactsList.add(contacts);
                        break;
                    }
                }
            }
        } else {
            for (UserInfo userInfo : userInfoList) {    //带关键字查询,查询到对应的好友
                Contacts contacts = new Contacts();
                contacts.setAge(userInfo.getAge());  //年龄
                contacts.setAvatar(userInfo.getLogo());  //头像
                contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));  //城市
                contacts.setGender(userInfo.getSex().toString()); //性别
                contacts.setNickname(userInfo.getNickName()); //名称
                contacts.setUserId(userInfo.getUserId().toString());
                contactsList.add(contacts);
            }
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(contactsList);

        return pageResult;
    }

    /**
     * 查询 评论（点赞、喜欢） 列表
     *
     * @param type
     * @param page
     * @param pageSize
     * @return 1、获取到评论表
     * 2、拿到type的用户id
     * 3、根据用户id查询数据库获取信息
     * 4、再一一对应的封装到返回前端的vo对象中
     */
    public PageResult messageCommentList(Integer type, Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);

        //获取到评论表
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);
        List<Comment> records = pageInfo.getRecords();

        //封装userId集合
        List<Long> userIds = new ArrayList<>();
        for (Comment comment : records) {
            userIds.add(comment.getUserId());
        }
        //构建查询条件查询数据库
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        //创建返回前端的MessageLike对象集合
        List<MessageLike> messageLikeList = new ArrayList<>();

        //封装数据
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {

                    MessageLike messageLike = new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));

                    messageLikeList.add(messageLike);
                    break;
                }
            }
        }
        pageResult.setItems(messageLikeList);
        return pageResult;
    }


    /**
     * 点赞
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return this.messageCommentList(1, page, pageSize);
    }

    /**
     * 评论
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return this.messageCommentList(2, page, pageSize);
    }


    /**
     * 喜欢
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return this.messageCommentList(3, page, pageSize);
    }


    /**
     * 公告
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementIPage = announcementService.queryList(page, pageSize);

        List<MessageAnnouncement> messageAnnouncements = new ArrayList<>();

        for (Announcement record : announcementIPage.getRecords()) {
            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());

            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
            messageAnnouncements.add(messageAnnouncement);

        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(messageAnnouncements);

        return pageResult;
    }
}
